class HomeController < ApplicationController
  
  # authenticates users and redirects to /items
  def login
    @logged_in_user = User.find_by_id(session[:user_id])
	if @logged_in_user
	  # already logged in
	  respond_to do |format|
		if @logged_in_user.permission_level == 'courier'
	      format.html { redirect_to edit_user_path(@logged_in_user) }
		  format.json { render :text => 'accepted', :status =>  :accepted }
		elsif @logged_in_user.permission_level == 'client'
	      format.html { redirect_to :controller => 'items', :action => 'outgoing' }
		  format.json { render :text => 'accepted', :status =>  :accepted }
		else
	      format.html { redirect_to :controller => 'items' }
		  format.json { render :text => 'accepted', :status =>  :accepted }
		end
	  end
	elsif request.post?
	  user = User.authenticate(params[:account_name], params[:password])
	  if user
	    session[:user_id] = user.id
		uri = session[:original_uri]
		session[:original_uri] = nil
		base_url = {:controller => 'items'}
		base_url.merge({:action => 'incoming'}) if ["client", "courier"].include? user.permission_level
		respond_to do |format|
		  format.html { redirect_to(uri || {:controller => 'items'}) }
		  format.json { render :text => 'accepted', :status => :accepted }
	    end
	  else
	    respond_to do |format|
  		  format.html { flash.now[:notice] = 'Invalid credentials' }
		  format.json { render :text => 'not_acceptable', :status => :not_acceptable }
		end
	  end
	else
	  respond_to do |format|
	    format.html # render view
		format.json { render :text => 'not_acceptable', :status => :not_acceptable }
	  end
	end
  end

  # logs the user out and redirects to /items/login
  def logout
    session[:user_id] = nil
	redirect_to :action => 'login'
  end

  # this is just for dev use
  def scaffold
    # the global styling looks bad, so skip it
    render :layout => false
  end
  
end
